package com.sdh.onlinemarket.filter;

import cn.hutool.json.JSONUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdh.onlinemarket.common.annotation.AdminToken;
import com.sdh.onlinemarket.common.annotation.PassToken;
import com.sdh.onlinemarket.common.annotation.UserLoginToken;
import com.sdh.onlinemarket.entity.Usersecure;
import com.sdh.onlinemarket.service.UsersecureService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 拦截器
 */
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    UsersecureService usersecureService;
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();


        Map<String, String> map = new HashMap<>();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(UserLoginToken.class)) {
            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
            if (userLoginToken.required()) {
                // 执行认证
                if (token == null) {
                    httpServletResponse.reset();
                    httpServletResponse.setCharacterEncoding("UTF-8");
                    httpServletResponse.setContentType("application/json;charset=UTF-8");
                    httpServletResponse.reset();
                    httpServletResponse.setCharacterEncoding("UTF-8");
                    httpServletResponse.setContentType("application/json;charset=UTF-8");
                    httpServletResponse.setStatus(401);
                    PrintWriter pw = httpServletResponse.getWriter();
//                    log.info("无token，请重新登录");
                    map.put("msg", "无token，请重新登录");
                    pw.write(JSONUtil.toJsonStr(map));
                    return false;
//                    throw new RuntimeException("无token，请重新登录");
                }
                // 获取 token 中的 user id
                String userId;
                try {
                    userId = JWT.decode(token).getAudience().get(0);
                } catch (JWTDecodeException j) {
                    httpServletResponse.reset();
                    httpServletResponse.setCharacterEncoding("UTF-8");
                    httpServletResponse.setContentType("application/json;charset=UTF-8");
                    httpServletResponse.setStatus(401);
                    PrintWriter pw = httpServletResponse.getWriter();
                    map.put("msg", "Token无效");
                    pw.write(JSONUtil.toJsonStr(map));
                    return false;
//                    throw new RuntimeException("401");
                }
                Usersecure usersecure = usersecureService.getOne(new QueryWrapper<Usersecure>().eq("account", userId));
                if (usersecure == null) {
                    httpServletResponse.reset();
                    httpServletResponse.setCharacterEncoding("UTF-8");
                    httpServletResponse.setContentType("application/json;charset=UTF-8");
                    httpServletResponse.setStatus(401);
                    PrintWriter pw = httpServletResponse.getWriter();
                    map.put("msg", "用户不存在,请重新登陆");
                    pw.write(JSONUtil.toJsonStr(map));
                    return false;
//                    throw new RuntimeException("用户不存在，请重新登录");
                }
                // 验证 token
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(usersecure.getPassword())).build();
                try {
                    jwtVerifier.verify(token);
                } catch (JWTVerificationException e) {
                    httpServletResponse.reset();
                    httpServletResponse.setCharacterEncoding("UTF-8");
                    httpServletResponse.setContentType("application/json;charset=UTF-8");
                    httpServletResponse.setStatus(401);
                    PrintWriter pw = httpServletResponse.getWriter();
                    map.put("msg", "Token已过期");
                    pw.write(JSONUtil.toJsonStr(map));
                    return false;
//                    throw new RuntimeException("401");
                }
                return true;
            }
        }
            //管理员权限注解
        if (method.isAnnotationPresent(AdminToken.class)) {
            AdminToken adminToken = method.getAnnotation(AdminToken.class);
            if (adminToken.required()) {
                // 执行认证
                if (token == null) {
                    httpServletResponse.reset();
                    httpServletResponse.setCharacterEncoding("UTF-8");
                    httpServletResponse.setContentType("application/json;charset=UTF-8");
                    httpServletResponse.setStatus(401);
                    PrintWriter pw = httpServletResponse.getWriter();
//                    log.info("无token，请重新登录");
                    map.put("msg", "无token，请重新登录");
                    pw.write(JSONUtil.toJsonStr(map));
                    return false;
//                    throw new RuntimeException("无token，请重新登录");
                }
                // 获取 token 中的 user id
                String userId;
                try {
                    userId = JWT.decode(token).getAudience().get(0);
                } catch (JWTDecodeException j) {
                    httpServletResponse.reset();
                    httpServletResponse.setCharacterEncoding("UTF-8");
                    httpServletResponse.setContentType("application/json;charset=UTF-8");
                    httpServletResponse.setStatus(401);
                    PrintWriter pw = httpServletResponse.getWriter();
                    map.put("msg", "Token无效");
                    pw.write(JSONUtil.toJsonStr(map));
                    return false;
//                    throw new RuntimeException("401");
                }
                Usersecure usersecure = usersecureService.getOne(new QueryWrapper<Usersecure>().eq("account", userId));
                if (usersecure == null) {
                    httpServletResponse.reset();
                    httpServletResponse.setCharacterEncoding("UTF-8");
                    httpServletResponse.setContentType("application/json;charset=UTF-8");
                    httpServletResponse.setStatus(401);
                    PrintWriter pw = httpServletResponse.getWriter();
                    map.put("msg", "用户不存在,请重新登陆");
                    pw.write(JSONUtil.toJsonStr(map));
                    return false;
//                    throw new RuntimeException("用户不存在，请重新登录");
                }
                if (!usersecure.getAuthority().equals("1")) {
                    httpServletResponse.reset();
                    httpServletResponse.setCharacterEncoding("UTF-8");
                    httpServletResponse.setContentType("application/json;charset=UTF-8");
                    httpServletResponse.setStatus(401);
                    PrintWriter pw = httpServletResponse.getWriter();
                    map.put("msg", "用户权限不足");
                    pw.write(JSONUtil.toJsonStr(map));
//                    throw new RuntimeException("用户权限不足");
                    return false;
                }

                // 验证 token
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(usersecure.getPassword())).build();
                try {
                    jwtVerifier.verify(token);
                } catch (JWTVerificationException e) {
                    httpServletResponse.reset();
                    httpServletResponse.setCharacterEncoding("UTF-8");
                    httpServletResponse.setContentType("application/json;charset=UTF-8");
                    httpServletResponse.setStatus(401);
                    PrintWriter pw = httpServletResponse.getWriter();
                    map.put("msg", "Token验证失败");
                    pw.write(JSONUtil.toJsonStr(map));
                    return false;
//                    throw new RuntimeException("401");
                }
                return true;
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}
